import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/intl.dart' hide TextDirection;

class MsgTextContentView extends StatelessWidget {
  final int? lastTime;
  final bool isReverse;
  final Function()? onTapHead;
  final Function()? onTapMsg;
  final Function()? onResendMsg;
  const MsgTextContentView({
    Key? key,
    this.isReverse = false,
    this.lastTime,
    this.onTapHead,
    this.onTapMsg,
    this.onResendMsg,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _MsgTimeView(
      time: 1590940800,
      lastTime: lastTime,
      isReverse: isReverse,
      seq: "msg.seq",
      child: _MsgHeadView(
        onTapHead: onTapHead,
        onReSendMsg: onResendMsg,
        child: GestureDetector(
          onTap: onTapMsg,
          behavior: HitTestBehavior.translucent,
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              "有什么可以帮助你？",
              textAlign: TextAlign.left,
            ),
          ),
        ),
      ),
    );
  }
}

/// 图片
class MsgImageContentView extends StatelessWidget {
  final int? lastTime;
  final bool isReverse;
  final Function()? onTapHead;
  final Function()? onTapMsg;
  final Function()? onResendMsg;
  final String imUid;
  const MsgImageContentView({
    Key? key,
    required this.imUid,
    this.lastTime,
    this.isReverse = false,
    this.onTapHead,
    this.onTapMsg,
    this.onResendMsg,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // final String path = msg.imageElem!.path ?? "";
    // V2TimImage? image;
    // if ((msg.imageElem?.imageList?.length ?? 0) > 0) {
    //   const int type = 1; // 缩略图
    //   msg.imageElem?.imageList?.forEach((V2TimImage? element) {
    //     if (element?.type == type) {
    //       image = element;
    //     }
    //   });
    // }
    return _MsgTimeView(
      lastTime: lastTime,
      time: 1590940800,
      isReverse: isReverse,
      child: _MsgHeadView(
        onTapHead: onTapHead,
        maxWidth: 0.5,
        onReSendMsg: onResendMsg,
        child: GestureDetector(
          onTap: onTapMsg,
          behavior: HitTestBehavior.translucent,
          child: PhysicalModel(
            color: Colors.red,
            borderRadius: BorderRadius.circular(8),
            clipBehavior: Clip.antiAlias,
            child: SizedBox(
              width: 100,
              height: 100,
            ),
            // child: IMImage(
            //   imageUrl: image?.url ?? "",
            //   userIdOrGroupId: imUid,
            //   fit: BoxFit.cover,
            //   fadeInDuration: Duration.zero,
            //   fadeOutDuration: Duration.zero,
            //   placeholder: (BuildContext context, String str) {
            //     if (path != '') {
            //       return Image.file(
            //         File(path),
            //         fit: BoxFit.cover,
            //         cacheWidth: 320,
            //       );
            //     }
            //     return Image.asset(
            //       AssetsUtils.article_article_training_placeholder,
            //       fit: BoxFit.scaleDown,
            //       width: 100,
            //       height: 100,
            //     );
            //   },
            //   errorWidget: (BuildContext context, String url, _) {
            //     if (path != '') {
            //       return Image.file(
            //         File(path),
            //         fit: BoxFit.cover,
            //         cacheWidth: 320,
            //       );
            //     }
            //     return Image.asset(
            //       AssetsUtils.article_article_training_placeholder,
            //       fit: BoxFit.cover,
            //       width: 100,
            //       height: 100,
            //     );
            //   },
            // ),
          ),
        ),
      ),
    );
  }
}

class MsgSystemView extends StatelessWidget {
  final String msg;
  const MsgSystemView({Key? key, required this.msg}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(bottom: 16.0),
          child: Text(
            msg,
            style: const TextStyle(
              color: Color(0xff515151),
              fontWeight: FontWeight.w400,
              fontFamily: "PingFangSC",
              fontStyle: FontStyle.normal,
              fontSize: 11.0,
            ),
          ),
        ),
      ],
    );
  }
}

class _MsgHeadView extends StatelessWidget {
  final Widget child;
  final Function()? onReSendMsg;
  final Function()? onTapHead;
  final double maxWidth;
  const _MsgHeadView({
    Key? key,
    required this.child,
    this.onReSendMsg,
    this.onTapHead,
    this.maxWidth = 0.84,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final bool isRight = true;
    return Align(
      alignment: isRight ? Alignment.topRight : Alignment.topLeft,
      child: Container(
        constraints: BoxConstraints(
          minWidth: 100,
          maxWidth: MediaQuery.of(context).size.width * maxWidth,
        ),
        alignment: isRight ? Alignment.topRight : Alignment.topLeft,
        child: Row(
          mainAxisAlignment: isRight ? MainAxisAlignment.end : MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Flexible(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Flexible(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      child: child,
                    ),
                  ),
                ],
              ),
            ),
            GestureDetector(
              onTap: onTapHead,
              behavior: HitTestBehavior.translucent,
              child: PhysicalModel(
                color: Colors.teal,
                clipBehavior: Clip.antiAlias,
                shape: BoxShape.circle,
                child: SizedBox(
                  width: 44,
                  height: 44,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MsgTimeView extends StatelessWidget {
  final Widget child;
  final int? time;
  final bool isReverse;
  final int? lastTime;
  final String? seq;
  const _MsgTimeView({Key? key, required this.child, this.time, this.isReverse = false, this.lastTime, this.seq})
      : super(key: key);

  bool _isShowTime() {
    // return true;
    if (lastTime == null) return isReverse;
    final int _time = (time ?? 0) * 1000;
    final int _lastTime = (lastTime ?? 0) * 1000;
    final DateTime _dTime = DateTime.fromMillisecondsSinceEpoch(_time);
    final DateTime _dLastTime = DateTime.fromMillisecondsSinceEpoch(_lastTime);
    final Duration d = _dTime.difference(_dLastTime);
    final int days = (_dTime.day - _dLastTime.day).abs();
    if (DateUtil.isToday(_time)) {
      return d.inMinutes.abs() >= 5;
    } else {
      return days >= 1;
    }
  }

  String _createTime() {
    final int _time = (time ?? 0) * 1000;
    final DateTime _dTime = DateTime.fromMillisecondsSinceEpoch(_time);
    if (DateUtil.isToday(_time)) {
      return DateFormat("HH:mm").format(DateTime.fromMillisecondsSinceEpoch(_time));
    } else if (DateUtil.isYesterday(_dTime, DateTime.now())) {
      return "昨天 ${DateFormat("HH:mm").format(DateTime.fromMillisecondsSinceEpoch(_time))}";
    } else if (DateUtil.isWeek(_time)) {
      return "${DateUtil.getWeekday(_dTime, languageCode: "zh")} ${DateFormat("HH:mm").format(DateTime.fromMillisecondsSinceEpoch(_time))}";
    } else {
      return DateFormat("yyyy/MM/dd HH:mm").format(DateTime.fromMillisecondsSinceEpoch(_time));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Visibility(
          visible: _isShowTime() && time != null,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 16),
            child: Text(
              _createTime(),
            ),
          ),
        ),
        child
      ],
    );
  }
}
